Skip to main content

Primitive types

There are five primitive data types in JavaScript:

  • Number
  • String
  • Boolean
  • Undefined
  • Null

Number

In JavaScript the number type includes both integer and floating-point value.

Example

var number1 = 35; // Written without decimal
var number2 = 35.0; // Written with decimal
var number3 = 3.14; // Written with decimal

String

A string is set of character enclosed inside single or double quotes.

Example

var string1 = "Hello world"; // Inside double quotes
var string2 = "This is a string"; // Inside single quotes
var string3 = 'This is "JavaScript"'; // Double quotes inside single quotes
var string4 = "This is 'JavaScript'"; // single quotes inside double quotes
var string5 = ""; // An empty string has both value and type, where value is ""

Boolean

Boolean has true and false values.

Example

var x = 5;
var y = 10;

if (x == y) {
// Checks true or false
console.log("True"); // If true
} else {
console.log("False"); // If false
}
Note

Booleans are mainly used for conditional testing.

Undefined and Null

A variable without any value assigned or value do not exist, then it's type will be undefined. In null type, the value of a variable is set to be null.

Work out

var car; // Value and type are undefined
console.log(car); // Expected output: undefined
console.log(typeof car); // Expected output: undefined

// Any variable can be set to a type undefined by
var x = 5; // x is assigned with a value of 5, so x data type is number
console.log(x); // Expected output: 5
var x = undefined; // x is re-assigned with a value of undefined, so x data type is undefined
console.log(x); // Expected output: undefined

// Any variable can be set to a type null by
var y = 9; // y is assigned with a value of 9
console.log(y); // Expected output: 9
var y = null; // y is re-assigned with a value of null
console.log(y); // Expected output: null

Example

// When using == and ===
var x;
var y = null;
if (x == y) {
// using ==
console.log(" x equal to y");
} else {
console.log(" x not equal to y");
}
// Expected output: x equal to y
if (x === y) {
// using ===
console.log(" x equal to y");
} else {
console.log(" x not equal to y");
}
// Expected output: x not equal to y

The == operator evaluate the value only, on this aspect the null and undefined are equal. But while using the === operator, it will evaluate the value and data type. We know that null and undefined are different data types. On this aspect they are not equal.

:::

Note

In JavaScript typeof operator returns the type of a variable.

var x = 5;
console.log(typeof x);
// expected output: number